import 'package:buttons_tabbar/buttons_tabbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/pages/teacher/evaluationClassReport.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/charts/evaluationLinguisticSkillsTreeView.dart';
import 'package:ichinesereader/widgets/charts/evaluationLinguisticTreeMap.dart';
import 'package:ichinesereader/widgets/charts/evaluationProficiencySkillProgressTreeView.dart';
import 'package:ichinesereader/widgets/buttons/floatingActionButtonsTeacherSwitchClass.dart';
import '../../themes/appTheme.dart';

late TabController evaluationTab;

class EvaluationSkillCenterForTeacher extends StatefulWidget {
  static const String routeName = '/teacher/evaluation/skillcenter';

  @override
  State<EvaluationSkillCenterForTeacher> createState() =>
      _EvaluationSkillCenterForTeacherState();
}

class _EvaluationSkillCenterForTeacherState
    extends State<EvaluationSkillCenterForTeacher>
    with SingleTickerProviderStateMixin {
  final EvaluationController controller = Get.find();
  final box = Hive.box('appconfig');
  String _classId = '';
  bool isTeacher = false;
  var _currentLevelOptions = Constants.levelEvaluationOptions;
  int _selectedType = 0;
  String _currentLevel = "level1";

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    evaluationTab = TabController(vsync: this, length: 4);
    if (isTeacher) {
      _classId = box.get(CacheManagerKey['currentclass'].toString());
    } else {
      _classId = '';
    }
    // if (controller.currentLevel.value.indexOf("HSK") > 0) {
    //   _levelOptions = Constants.hskEvaluationOptions;
    // } else if (controller.currentLevel.value.indexOf(RegExp(r'\d')) < 0) {
    //   _levelOptions = Constants.actflEvaluationOptions;
    // }
    super.initState();
  }

  buildFloatingLevelButtons() {
    List<String> levelTypes = Constants.levelStandardTypes
        .where((element) => element != 'YCT')
        .toList();

    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: levelTypes
          .map((levelType) => Padding(
                padding: const EdgeInsets.only(bottom: 8.0),
                child: SizedBox(
                  width: 90.0,
                  height: 30.0,
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 3.0),
                    child: MaterialButton(
                      color: Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : Get.theme.primaryColorLight,
                      child: Text(
                        levelType.toString(),
                        style: TextStyle(color: Colors.black),
                      ),
                      //heroTag:
                      //tooltip: levelType.tr,
                      onPressed: () {
                        var level = "level1";
                        if (levelType == "HSK") {
                          _currentLevelOptions = Constants.hskEvaluationOptions;
                          level = "HSK1";
                        } else if (levelType == "ACTFL") {
                          _currentLevelOptions =
                              Constants.actflEvaluationOptions;
                          level = "Novice-Low";
                        } else {
                          _currentLevelOptions =
                              Constants.levelEvaluationOptions;
                          level = "level1";
                        }
                        setState(() {
                          _currentLevel = level;
                          _currentLevelOptions = _currentLevelOptions;
                        });
                        controller.updateCurrentLevel(level);
                        var currentTabIdx = evaluationTab.index;
                        if (currentTabIdx == 0) {
                          controller.fetchEvaluationProficiencySkillsData(
                              _classId, level, '');
                        } else if (currentTabIdx == 1) {
                          controller.fetchEvaluationLinguisticKnowledgesData(
                              _classId, level, '');
                        } else if (currentTabIdx == 2) {
                          controller.fetchEvaluationSkillPointsData(
                              _classId, level);
                        } else if (currentTabIdx == 3) {
                          controller.fetchEvaluationClassReportData(
                              _classId, level);
                        }
                      },
                      elevation: 5,
                      splashColor: Colors.grey,
                      //child: Text(levelType),
                    ),
                  ),
                ),
              ))
          .toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build teacher evaluation skills center');

    final isMediumScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenMediumSize;

    List<String> levelTypes = Constants.levelStandardTypes
        .where((element) => element != 'YCT')
        .toList();

    return DefaultTabController(
      length: 4,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Column(
          children: [
            isMediumScreen
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // buildFloatingLevelButtons(),
                      Container(
                        height: 30.0,
                        margin: EdgeInsets.only(bottom: 9.0),
                        alignment: Alignment.center,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: levelTypes.length,
                          itemBuilder: ((context, index) {
                            return Padding(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 3.0,
                              ),
                              child: ChoiceChip(
                                padding: EdgeInsets.symmetric(horizontal: 18.0),
                                shape: BeveledRectangleBorder(
                                  borderRadius: BorderRadius.circular(1.0),
                                ),
                                backgroundColor: AppTheme.colors.disableBtn,
                                label: Text(
                                  levelTypes[index],
                                  style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Colors.white),
                                ),
                                selectedColor: Get.isDarkMode
                                    ? Colors.white
                                    : AppTheme.colors.orangeBtn,
                                selected: _selectedType == index,
                                onSelected: (selected) {
                                  var level = "level1";
                                  if (levelTypes[index] == "HSK") {
                                    _currentLevelOptions =
                                        Constants.hskEvaluationOptions;
                                    level = "HSK1";
                                  } else if (levelTypes[index] == "ACTFL") {
                                    _currentLevelOptions =
                                        Constants.actflEvaluationOptions;
                                    level = "Novice-Low";
                                  } else {
                                    _currentLevelOptions =
                                        Constants.levelEvaluationOptions;
                                    level = "level1";
                                  }
                                  setState(() {
                                    _selectedType = selected ? index : 0;
                                    _currentLevel = level;
                                    _currentLevelOptions = _currentLevelOptions;
                                  });
                                  controller.updateCurrentLevel(
                                      level.replaceAll("level", ""));
                                  var currentTabIdx = evaluationTab.index;
                                  if (currentTabIdx == 0) {
                                    controller
                                        .fetchEvaluationProficiencySkillsData(
                                            _classId,
                                            level.replaceAll("level", ""),
                                            '');
                                  } else if (currentTabIdx == 1) {
                                    controller
                                        .fetchEvaluationLinguisticKnowledgesData(
                                            _classId,
                                            level.replaceAll("level", ""),
                                            '');
                                  } else if (currentTabIdx == 2) {
                                    controller.fetchEvaluationSkillPointsData(
                                        _classId,
                                        level.replaceAll("level", ""));
                                  } else if (currentTabIdx == 3) {
                                    controller.fetchEvaluationClassReportData(
                                        _classId,
                                        level.replaceAll("level", ""));
                                  }
                                },
                              ),
                            );
                          }),
                        ),
                      ),
                      ButtonsTabBar(
                        buttonMargin: EdgeInsets.only(bottom: 9.0, right: 9.0),
                        labelStyle: TextStyle(
                            color: Get.isDarkMode
                                ? Colors.black
                                : AppTheme.colors.lightOrange),
                        unselectedBackgroundColor: Get.isDarkMode
                            ? Get.theme.primaryColor
                            : Colors.grey[300],
                        backgroundColor: Get.isDarkMode
                            ? Colors.white
                            : AppTheme.colors.orangeBtn,
                        controller: evaluationTab,
                        contentPadding: EdgeInsets.symmetric(horizontal: 12.0),
                        radius: 3.0,
                        tabs: [
                          Tab(text: 'Proficiency'),
                          Tab(text: 'Linguistics'),
                          Tab(text: 'Language Skills'),
                          Tab(text: 'Report'),
                        ],
                      ),
                    ],
                  )
                : Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      // buildFloatingLevelButtons(),
                      Container(
                        height: 30.0,
                        width: 300.0,
                        margin: EdgeInsets.only(bottom: 9.0),
                        alignment: Alignment.center,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemCount: levelTypes.length,
                          itemBuilder: ((context, index) {
                            return Padding(
                              padding: const EdgeInsets.only(right: 6.0),
                              child: ChoiceChip(
                                padding: EdgeInsets.symmetric(horizontal: 18.0),
                                shape: BeveledRectangleBorder(
                                  borderRadius: BorderRadius.circular(1.0),
                                ),
                                backgroundColor: AppTheme.colors.disableBtn,
                                label: Text(
                                  levelTypes[index],
                                  style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Colors.white),
                                ),
                                selectedColor: Get.isDarkMode
                                    ? Colors.white
                                    : AppTheme.colors.orangeBtn,
                                selected: _selectedType == index,
                                onSelected: (selected) {
                                  var level = "level1";
                                  if (levelTypes[index] == "HSK") {
                                    _currentLevelOptions =
                                        Constants.hskEvaluationOptions;
                                    level = "HSK1";
                                  } else if (levelTypes[index] == "ACTFL") {
                                    _currentLevelOptions =
                                        Constants.actflEvaluationOptions;
                                    level = "Novice-Low";
                                  } else {
                                    _currentLevelOptions =
                                        Constants.levelEvaluationOptions;
                                    level = "level1";
                                  }
                                  setState(() {
                                    _selectedType = selected ? index : 0;
                                    _currentLevel = level;
                                    _currentLevelOptions = _currentLevelOptions;
                                  });
                                  controller.updateCurrentLevel(
                                      level.replaceAll("level", ""));
                                  var currentTabIdx = evaluationTab.index;
                                  if (currentTabIdx == 0) {
                                    controller
                                        .fetchEvaluationProficiencySkillsData(
                                            _classId,
                                            level.replaceAll("level", ""),
                                            '');
                                  } else if (currentTabIdx == 1) {
                                    controller
                                        .fetchEvaluationLinguisticKnowledgesData(
                                            _classId,
                                            level.replaceAll("level", ""),
                                            '');
                                  } else if (currentTabIdx == 2) {
                                    controller.fetchEvaluationSkillPointsData(
                                        _classId,
                                        level.replaceAll("level", ""));
                                  } else if (currentTabIdx == 3) {
                                    controller.fetchEvaluationClassReportData(
                                        _classId,
                                        level.replaceAll("level", ""));
                                  }
                                },
                              ),
                            );
                          }),
                        ),
                      ),

                      ButtonsTabBar(
                        buttonMargin: EdgeInsets.only(bottom: 9.0, left: 9.0),
                        labelStyle: TextStyle(
                            color: Get.isDarkMode
                                ? Colors.black
                                : AppTheme.colors.lightOrange),
                        unselectedBackgroundColor: Get.isDarkMode
                            ? Get.theme.primaryColor
                            : Colors.grey[300],
                        backgroundColor: Get.isDarkMode
                            ? Colors.white
                            : AppTheme.colors.orangeBtn,
                        controller: evaluationTab,
                        contentPadding: EdgeInsets.symmetric(horizontal: 12.0),
                        radius: 3.0,
                        tabs: [
                          Tab(text: 'Proficiency'),
                          Tab(text: 'Linguistics'),
                          Tab(text: 'Language Skills'),
                          Tab(text: 'Report'),
                        ],
                      ),
                    ],
                  ),
            Container(
              height: 30.0,
              margin: EdgeInsets.only(bottom: 9.0),
              alignment: Alignment.center,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: _currentLevelOptions.length,
                itemBuilder: ((context, index) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 3.0,
                    ),
                    child: ChoiceChip(
                      padding: EdgeInsets.symmetric(horizontal: 9.0),
                      shape: BeveledRectangleBorder(
                        side: BorderSide(color: Colors.white, width: 0.3),
                        borderRadius: BorderRadius.circular(1.0),
                      ),
                      backgroundColor: hexStringToHexInt(
                        _currentLevelOptions[index].color.toString(),
                      ),
                      label: Text(
                        _currentLevelOptions[index]
                            .label
                            .toString()
                            .replaceAll('Level 0', 'N/A')
                            .replaceAll('Level ', ''),
                        style: TextStyle(
                            fontWeight: FontWeight.bold, color: Colors.white),
                      ),
                      selectedColor: Colors.black,
                      selected: _currentLevelOptions.indexWhere(
                              (element) => element.value == _currentLevel) ==
                          index,
                      onSelected: (selected) {
                        setState(() {
                          _currentLevel = selected
                              ? _currentLevelOptions[index].value!
                              : _currentLevelOptions[0].value!;
                        });
                        // if (value == false) return;
                        var item = _currentLevelOptions[index];
                        var currentLevel =
                            item.value.toString().replaceAll('level', '');
                        controller.updateCurrentLevel(currentLevel);
                        var currentTabIdx = evaluationTab.index;
                        if (currentTabIdx == 0) {
                          controller.fetchEvaluationProficiencySkillsData(
                              _classId, currentLevel, '');
                        } else if (currentTabIdx == 1) {
                          controller.fetchEvaluationLinguisticKnowledgesData(
                              _classId, currentLevel, '');
                        } else if (currentTabIdx == 2) {
                          controller.fetchEvaluationSkillPointsData(
                              _classId, currentLevel);
                        } else if (currentTabIdx == 3) {
                          controller.fetchEvaluationClassReportData(
                              _classId, currentLevel);
                        }
                      },
                    ),
                  );
                }),
              ),
            ),
            Expanded(
              child: TabBarView(
                controller: evaluationTab,
                children: [
                  EvaluationProficiencySkillsTreeview(),
                  //EvaluationProficiencySkillsTreeGraph(),
                  EvaluationLinguisticTreeMap(),
                  //EvaluationLinguisticSkillsTreeGraph(),
                  EvaluationLinguisticSkillsTreeView(),
                  EvaluationClassReportForTeacher(),
                ],
              ),
            ),
          ],
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
        floatingActionButton: FloatingActionButtonsTeacherSwitchClass(),
      ),
    );
  }
}
